<?php


namespace App\Repositories;


use App\Models\Location as Model;
use Illuminate\Support\Facades\DB;
use LTools\Repositories\RepositoryAbstract;
use Symfony\Component\Translation\Exception\NotFoundResourceException;

class Location extends RepositoryAbstract
{
    /**
     * Location constructor.
     * @param Model $model
     * @author luffyzhao@vip.126.com
     */
    public function __construct(Model $model)
    {
        $this->model = $model;
    }


    /**
     * @param array $attributes
     * @author luffyzhao@vip.126.com
     */
    public function batchCreate(array $attributes = [])
    {
        DB::transaction(function () use ($attributes) {
            for ($row = 1; $row <= $attributes['row']; $row++) {
                for ($column = 1; $column <= $attributes['column']; $column++) {
                    for ($layer = 1; $layer <= $attributes['layer']; $layer++) {
                        $attributes['code'] = $this->getCode($attributes['partition'], $attributes['attribute'], $row, $column, $layer);
                        parent::create($attributes);
                    }
                }
            }
        });

    }

    /**
     * @param $attribute
     * @param $partition
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function free($attribute, $partition = ''){
        $query = $this->model->newQuery()
            ->where('count', '=', 0)
            ->where('status', '=', 1)
            ->where('attribute', '=', $attribute);
        if(!empty($partition)){
            $query->where('partition', '=', $partition);
        }
        return $query->orderBy('code')->first();
    }

    /**
     * @param string $partition 分区代码
     * @param int $attribute
     * @param int $row 行
     * @param int $column 列
     * @param int $layer 层
     * @return string
     * @author luffyzhao@vip.126.com
     */
    protected function getCode(string $partition, int $attribute, int $row, int $column, int $layer)
    {
        $attributes = ['L', 'B', 'K'];
        return sprintf(
            '%s_%s_%s_%s_%s',
            $partition,
            $attributes[$attribute],
            str_pad($row, 2, '0', STR_PAD_LEFT),
            str_pad($column, 2, '0', STR_PAD_LEFT),
            str_pad($layer, 2, '0', STR_PAD_LEFT)
        );
    }


}
